# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
import requests
from pyquery import PyQuery as pq
from toolFunctions import response, validator
from articleModel.models import Article
from userModel.models import User
import sys


reload(sys)
sys.setdefaultencoding('utf8')


def fetch_zhihu_home(request):
    headers = {
        "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
    }

    #   获取文章id
    r = requests.get('http://daily.zhihu.com', headers=headers)
    doc = pq(r.text)
    links = doc('.main-content-wrap .row .col-lg-4 .wrap .link-button')
    article_ids = []
    for item in links.items():
        href = item.attr("href")

        if validator.is_empty(href):
            continue

        try:
            article_id = href.replace('/story/', '')
            if not validator.is_empty(article_id):
                article_ids.append(int(article_id))
        except:
            continue

    print '文章id获取完成====================='
    print article_ids

    #   获取文章详情
    for article_id in article_ids:
        r = requests.get('http://daily.zhihu.com/story/' + str(article_id), headers=headers)
        doc = pq(r.text)

        author_info = {
            "password": "123123",
            "username": "",
            "email": "",
            "head_img": "",
            "description": ""
        }
        article_info = {
            "picture_title": doc('.App-main .DailyHeader .DailyHeader-title').text() or '',
            "picture": doc('.App-main .DailyHeader .DailyHeader-image img').attr('src') or '',
            "title": "",
            "content": "",
            "status": 1
        }
        for item in doc('.content-inner .question').items():
            # if not item('.question-title').text():
            #     continue

            #   文章信息
            article_info["title"] = item('.question-title').text() or article_info["picture_title"]
            article_info["content"] = item('.answer .content').html() or ''
            #   作者信息
            author_info["username"] = item('.answer .meta .author').text().replace('，', '') or ''
            author_info["head_img"] = item('.answer .meta .avatar').attr('src') or ''
            author_info["description"] = item('.answer .meta .bio').text() or ''
            print "作者名称=========================", author_info["username"]
            try:
                author_info["email"] = str(author_info["username"]).encode('hex') + '@zhihu.com'   # 作者信息：邮箱初始化
                print "作者邮箱=========================", author_info["email"]
            except:
                pass
            break

        if author_info["username"] and author_info["email"]:
            user = User.objects.filter(email=author_info["email"]).first()

        article = Article.objects.filter(title=article_info["title"]).first()
        if article is None:
            if user is None:
                user = User(password=author_info["password"], username=author_info["username"], email=author_info["email"], head_img=author_info["head_img"], description=author_info["description"])
                user.save()
                print "用户创建成功=========================", user.id
            article = Article(picture_title=article_info["picture_title"], picture=article_info["picture"], title=article_info["title"], content=article_info["content"], status=article_info["status"], user_id=user.id)
            article.save()
            print "文章创建成功=========================", article.id

    return response.success()


if __name__ == '__main__':
    fetch_zhihu_home()